<html>
<head>
<title></title>

<script src="/static/js/jquery.min.js" type="text/javascript"></script>
<script src="/static/js/jquery.json-1.3.js" type="text/javascript"></script>
<script src="/static/js/peerscape.js" type="text/javascript"></script>

<script language="javascript">


var pixelsize = 6;
var skyheight = 40;
var song    = 'day';

var tool = 'flower1';

var music = true;

var flist = [];

var username;
var useriid;

function audioelement(song,auto,loop)
{
  var audioauto = '';
  var embedauto = ' autostart="false"';
  if(auto)
  {
    audioauto = ' autoplay="autoplay"';
    embedauto = ' autostart="true"';
  }

  var audioloop = '';
  var embedloop = ' loop="false"';
  if(loop)
  {
    audioloop = ' loop="loop"';
    embedloop = ' loop="true"';
  }
  var audioelem = '<audio src="' + song + '"'+audioauto+audioloop+'><embed src="' + song + '"'+embedauto+embedloop+'></embed></audio>';
  return(audioelem);
}

function togrid(x)  { return (x/pixelsize|0); }
function topix(x)   { return x*pixelsize      }

function play(sound)
{
  $('#speaker').html(audioelement(sound,true,false));
}

function flower(id, x, y, image, florist)
{
  var shiftf={
  'flower1': {'x': -9 ,'y': -16},
  'flower2': {'x': -8 ,'y': -16},
  'flower3': {'x': -6 ,'y': -16},
  }

  var xc = topix(x+shiftf[image]['x']);
  var yc = topix(y+shiftf[image]['y']+skyheight);

  var elem = '<img id="' + id + '"onClick="rmflower(' + id + ')" class="flower" src="'+ image +'.png" alt="" style="left: '+xc+'px; top: '+yc+'px;" title="a flower from ' +florist + '"/>';

  $('#flowerbed').append(elem);
}

function unload(id)
{
    play('delete.wav');
    $('#'+id).remove();
}

function rmflower(id)
{
  if(tool == 'tool-r')
  {
    unstore(id);
  }
}

function unstore(id)
{
  $.post( '/delete/flowers/' + id + '.json', {'value': ''});
}

function store(id, thingie)
{
  $.post( '/post/flowers/' + id + '.json', {'value': $.toJSON(thingie)});
}

function validposition(x,y)
{
  var width =  131-16;
  var height = 112-skyheight;


  if(y > 0 && y < height-1 && x > 0 && x < width-2)
  {
    return true;
  }
  return false;
}

function loadflower(id)
{
  var loader = function(elems)
  {
    if(elems.length > 4)
    {
      var lid = elems[0];
      var lx = parseInt(elems[1]);
      var ly = parseInt(elems[2]);
      var ltool = elems[3];
      var lflorist = elems[4];

      if(validposition(lx,ly))
      {
        flower(lid, lx, ly, ltool, lflorist);
        play('add.wav');
      }
      else
      {
        unstore(id);
      }
    }
  }
  var filename = '/get/flowers/' + id + '.json';
  $.get( filename, {}, loader, "json" );
}


function loadflowers()
{

  var traverser = function(data)
  {
    if(data)
    { 
      for (var i in data)
      {
        data[i] = data[i].split('.json')[0];
      }
      //alert('before\n' + $.toJSON(flist) + '\n' + $.toJSON(data));
      var i = 0;
      while(i < flist.length)
      {
        //alert('while ('+i+'/'+flist.length+')\n' + $.toJSON(flist) + '\n' + $.toJSON(data));
/*
        //window.status=$.toJSON(data.length);
*/
        if(flist[i] != data[0])
        {
          //alert('diff('+i+')\n' + $.toJSON(flist) + '\n' + $.toJSON(data));
          var removed = flist[i];
          flist.splice(i,1);
          unload(removed);
        }
        else
        {
          data.shift();
          i++;
        }
      }
      //alert('ones to add\n'+$.toJSON(flist) + '\n' + $.toJSON(data));
      for (var i in data)
      {
        var id = data[i];
        flist.push(id);
        loadflower(id);
      }
    }
  }

  var clearthem = function(e)
  {
    if(flist.length == 1)
    {
      unload(flist[0]);
      flist = [];
    }
  }

  $.ajax({
      type: 'GET',
      url: '/list/flowers/',
      async: false,
      success: traverser,
      error: clearthem,
      dataType: 'json'
  });

}

function randid()
{
  return( Math.random() * Math.pow(2,30) | 0);
}

function infohandler(data)
{
  username = data['viewer']['name'];
  useriid = data['viewer']['iid'];
}

function place(x, y)
{
  if(validposition(x,y))
  {  
  var id = randid();
  store(id, [id,x,y,tool,username,useriid]);
  }
}

function move(e)
{
    var cx = e.clientX;
    var cy = e.clientY;
    var x = togrid(cx);
    var y = togrid(cy)-skyheight;
    /*window.status=$.toJSON([cx,cy,x,y]);*/
}

function click(e)
{
  if(tool != 'tool-r')
  {
    var cx = e.clientX;
    var cy = e.clientY;
    var x = togrid(cx);
    var y = togrid(cy)-skyheight;
    place(x, y);
  }

}

function settool(x)
{

  $('#'+tool).removeClass('selected');
  tool=x
  $('#'+x).addClass('selected');

  if(tool == 'tool-r')
  {
     $('#mainframe').addClass('rmtool')
  }
  else
  {
     $('#mainframe').removeClass('rmtool')
  }
  storesettings();
}

function togglemusic()
{
  if(music)
  {
    musicoff();
  }
  else
  {
    musicon();
  }
  storesettings();
}

function musicon()
{
  music = true;
  $('#mainframe').addClass('music');
  var ae = audioelement(song+'.ogg', true, true);
  document.getElementById('song').innerHTML=ae;
}

function musicoff()
{
  music = false;
  $('#mainframe').removeClass('music');
  document.getElementById('song').innerHTML='';
}

function storesettings()
{
  document.cookie = 'music=' + music + ';';
  document.cookie = 'tool=' + tool + ';';
}

function loadsettings()
{
  var cookies = {}
  entries = document.cookie.split('; ')
  for (var count in entries)
  {
    var pair = entries[count].split('=');
    if( pair.length == 2)
    {
      cookies[pair[0]] = pair[1];
    }
  }
 
  music = (cookies['music'] == 'false') ? false : true;
 
  if (music)
  {
    musicon();
  }
  else
  {
    musicoff();
  }

  if (cookies['tool'] == 'flower2') { settool('flower2'); }
  else if (cookies['tool'] == 'flower3') { settool('flower3'); }
  else if (cookies['tool'] == 'tool-r')  { settool('tool-r'); }
  else { settool('flower1'); }

}

function timeofday()
{

  var now = new Date;
  var time = now.getHours();

  var pic     = 'sun';
  var message = 'Hello!';
  if( time > 20 || time < 9 )
  {
    pic     = 'moon';
    message = 'Good night!';
    song    = 'night';
    $('#mainframe').addClass('night')
  }

  $('#flowerbed').append('<img id="celestial" src="' + pic + '.png" alt="' + pic + '" title="' + message + '"/>');

}

function updateloop()
{
  loadflowers();
  setTimeout ( 'updateloop()', 1000 );
}

function init()
{
  timeofday();
  loadsettings();

  $.get('/content/info',{},infohandler,'json');

  peerscape.common.resize();
  peerscape.common.scrollToTop();

  updateloop();
}

window.onmousemove = move;
window.onclick = click;
window.onload = init;
</script>

<link rel="stylesheet" href="flower.css" type="text/css" />

</head>

<body>
<div id="mainframe">
  <div id="sky"></div>
  <div id="ground"></div>
  <div class="glass top"></div>
  <div class="glass bottom"></div>
  <div class="glass left"></div>
  <div class="glass right"></div>
  <div id="toolbar" class="toolbar">
    <img class="tool" id="flower1" onclick="settool('flower1')" src="ficon1.png" title="pink flower seed" /><br />
    <img class="tool" id="flower2" onclick="settool('flower2')" src="ficon2.png" title="orange flower seed" /><br />
    <img class="tool" id="flower3" onclick="settool('flower3')" src="ficon3.png" title="white flower seed" /><br />
    <hr  onclick="loadflowers();"/>
    <img class="tool" id="tool-r" onclick="settool('tool-r')" src="sicon.png" title="flower eater" /><br/>
    <a class="secretlink" href="http://iki.fi/toni.ruottu/" target="_blank"><img id="autograph" src="autograph.png" alt="" title="Thanks for using the software!" /></a>
    <img class="toggle" id="mtoggle" onClick="togglemusic();" src="mtoggle.png" alt="" title="toggle background music" />
  </div>
  <p id="flowerbed"></p>
  <div class="secret">
    <span id="song" class="secret"></span>
    <span id="speaker" class="secret"></span>
  </div>
</div>
</body>
</html>
